package cn.fl.project.service.impl;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.constant.WebBaseConstant;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.project.api.ICalQuatPrpsApiService;
import cn.fl.project.constant.PrjQuatPrpsConstant;
import cn.fl.project.dto.CalQuatPrpsDTO;
import cn.fl.project.service.ICalQuatPrpsService;
import cn.fl.project.transform.CalQuatPrpsVOTransform;
import cn.fl.project.vo.CalPaySchVO;
import cn.fl.project.vo.CalQuatPrpsFeeVO;
import cn.fl.project.vo.CalQuatPrpsVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


/**
 * @Description: 报价器-方案 客户端服务层接口实现
 * @Description: 业务层方法名称前缀：新增：add* 删除：remove* 修改：modify* 查询对象：select* get* 批量：batch* 查询集合：search*
 */
@Service
public class CalQuatPrpsServiceImpl implements ICalQuatPrpsService {

	/**
	 * 日志
	 */
	private static final Logger logger = LoggerFactory.getLogger(CalQuatPrpsServiceImpl.class);
	
	/**
	 * 自定义 API 自行注入需要的API服务
	 */
	@Autowired
	private ICalQuatPrpsApiService calQuatPrpsApiService;
    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;
	@Override
	public CalQuatPrpsVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.info(logger, "selectById", "主键参数不能为空!", CurrentThreadContext.getCurrentUserName());
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "获取对象主键不能为空!");
		}
		//TODO 业务逻辑
		CalQuatPrpsDTO dto = null;//this.自定义ApiService.selectCalQuatPrpsDTOById(id);
		return CalQuatPrpsVOTransform.toVO(dto);
	}

	@Override
	public Long add(CalQuatPrpsVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.info(logger, "add", "新增对象不存在!");
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"新增对象不存在!");
		};
		//return this.calQuatPrpsApiService.add(CalQuatPrpsVOTransform.toDTO(entity));
		//TODO 业务逻辑
		return null;
	}

	@Override
	public boolean removeById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.info(logger, "removeById", "删除对象主键不能为空!");
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"删除对象主键不能为空!");
		};
		//return this.calQuatPrpsApiService.removeCalQuatPrpsDTOById(id);
		//TODO 业务逻辑
		return false;
	}
	
	/**
     * 删除
     * @param ids
     * @return
     */
    public boolean removeByIds(List<Long> ids)throws BaseException{
		if(CollectionUtils.isEmpty(ids)){
			BaseLogUtils.info(logger, "removeByIds", "删除主键参数集合不能为空!", CurrentThreadContext.getCurrentUserName());
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"删除对象主键不能为空!");
		};
		return false;
    }

	@Override
	public boolean modify(CalQuatPrpsVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.info(logger, "modify", "修改对象不能为空!");
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"修改对象不能为空!");
		};
		//return this.calQuatPrpsApiService.modifyCalQuatPrpsDTO(CalQuatPrpsVOTransform.toDTO(entity));
		//TODO 业务逻辑
		return false;
	}

	@Override
	public Pager searchListPage(Pager page) throws BaseException{
		if(null == page){
			page = new Pager();
		}
        page =  this.calQuatPrpsApiService.searchCalQuatPrpsListPage(page);
		if(CollectionUtils.isNotEmpty(page.getResultList())){
            List<CalQuatPrpsVO> prpsDTOList = CalQuatPrpsVOTransform.toVOList((List<CalQuatPrpsDTO>)page.getResultList());
            setDictionaryOption(prpsDTOList,CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd());
            page.setResultList(prpsDTOList);
        }
		return page;
	}

    @Override
    public boolean removeCalQuatPrpsAndDetailByIds(List<Long> idList) throws BaseException {
        return this.calQuatPrpsApiService.removeCalQuatPrpsAndDetailByIds(idList);
    }

    @Override
    public CalQuatPrpsVO selectCalQuatProsAndDetailById(Long prpsId) {
        CalQuatPrpsVO vo  = CalQuatPrpsVOTransform.toVO(this.calQuatPrpsApiService.selectCalQuatProsAndDetailById(prpsId));
        vo = getTotalValue(vo);
        //setFeeDictionary
        if(CollectionUtils.isNotEmpty(vo.getFeeList())){
            setCalQuatPrpsFeeDictOption(vo.getFeeList(),CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd());
        }
        List<CalQuatPrpsVO> prpsList = new  ArrayList<CalQuatPrpsVO>();
        prpsList.add(vo);
        setDictionaryOption(prpsList,CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd());
        sortPayList(vo.getPayList());
        return vo;
    }

    public CalQuatPrpsVO calQuatPrpsCalculate(CalQuatPrpsVO prjQuatPrps) throws BaseException {
        prjQuatPrps = CalQuatPrpsVOTransform.toVO(this.calQuatPrpsApiService.calQuatPrpsCalculate(CalQuatPrpsVOTransform.toDTO(prjQuatPrps)));
        prjQuatPrps = getTotalValue(prjQuatPrps);
        return prjQuatPrps;
    }

    @Override
    public Long modifyGenCalQuatPrps(CalQuatPrpsVO prjQuatPrps) throws BaseException {
        return calQuatPrpsApiService.modifyGenCalQuatPrps(CalQuatPrpsVOTransform.toDTO(prjQuatPrps));
    }


    private void setCalQuatPrpsFeeDictOption(List<CalQuatPrpsFeeVO> list, String sysCd, String orgCd) {
        Map<String, String> quatCntWayCdMap = this.sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, DictionaryConstant.CODE_PRJ_QUAT_CNT_WAY_CD);
        Map<String, String> quatCalBaseCdMap = this.sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, DictionaryConstant.CODE_PRJ_QUAT_CAL_BASE_CD);
        Map<String, String> quatPrpsFeeTypCdMap = this.sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, DictionaryConstant.CODE_PRJ_QUAT_FEE_TYP_CD);
        Map<String, String> yesNoMap = this.sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, DictionaryConstant.CODE_SYS_YES_NO_CD);
        if(CollectionUtils.isNotEmpty(list)){
            for (CalQuatPrpsFeeVO calQuatPrpsFeeVO : list) {
                if(quatCntWayCdMap.containsKey(calQuatPrpsFeeVO.getCntWayCd())){
                    calQuatPrpsFeeVO.setCntWayCdNm(quatCntWayCdMap.get(calQuatPrpsFeeVO.getCntWayCd()));
                }
                if(quatCalBaseCdMap.containsKey(calQuatPrpsFeeVO.getCalBaseCd())){
                    calQuatPrpsFeeVO.setCalBaseCdNm(quatCalBaseCdMap.get(calQuatPrpsFeeVO.getCalBaseCd()));
                }
                if(quatPrpsFeeTypCdMap.containsKey(calQuatPrpsFeeVO.getFeeTypCd())){
                    calQuatPrpsFeeVO.setFeeTypCdNm(quatPrpsFeeTypCdMap.get(calQuatPrpsFeeVO.getFeeTypCd()));
                }
                if(null!=calQuatPrpsFeeVO.getIsFixedAmt()){
                    if(yesNoMap.containsKey(calQuatPrpsFeeVO.getIsFixedAmt().toString())){
                        calQuatPrpsFeeVO.setIsFixedAmtNm(yesNoMap.get(calQuatPrpsFeeVO.getIsFixedAmt().toString()));
                    }
                }
            }
        }
    }
    private void setDictionaryOption(List<CalQuatPrpsVO> quatList,String sysCd,String orgCd) {

        Map<String, String> lsCalWayCdMap = this.sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, DictionaryConstant.CODE_PRJ_LS_CAL_WAY_CD);
        Map<String, String> intRateWayCdMap = this.sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, DictionaryConstant.CODE_PRJ_INT_RATE_WAY_CD);
        Map<String, String> dpstHdlWayCdMap = this.sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, DictionaryConstant.CODE_PRJ_QUAT_DPST_HDL_WAY_CD);
        Map<String, String> expHdlWayCdMap = this.sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, DictionaryConstant.CODE_PRJ_QUAT_EXP_HDL_WAY_CD);
        Map<String, String> payWayCdMap = this.sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, DictionaryConstant.CODE_PRJ_QUAT_PAY_WAY_CD);
        Map<String, String> lsPdUntCdMap = this.sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, DictionaryConstant.CODE_PRJ_QUAT_LS_PD_UNT_CD);
        Map<String, String> noPayWayCdMap = this.sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, DictionaryConstant.CODE_PRJ_NO_PAY_WAY_CD);
        Map<String, String> yesOrNoCdMap = this.sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, DictionaryConstant.CODE_SYS_YES_NO_CD);
        Map<String, String> prpsQuatTypMap = this.sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, DictionaryConstant.CODE_PRJ_QUAT_PRPS_PRD_TYP_CD);
        Map<String, String> prdTypMap = this.sysDictionaryApiService.searchGroupToMap("15000", orgCd, DictionaryConstant.CODE_PRD_TYP_CD);
//        Map<String, String> dsCdMap = sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, DictionaryConstant.CODE_SYS_DS_CD);//数据来源
        //数据来源sys0001变更渠道代码sys0047
        Map<String, String> dsCdMap = sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, WebBaseConstant.CODE_SYS_CHL_CD);
        if(CollectionUtils.isNotEmpty(quatList)){
            for (CalQuatPrpsVO quat : quatList) {
                if(null!=quat){
                    if(lsCalWayCdMap.containsKey(quat.getLsCalWayCd())){
                        quat.setLsCalWayCdNm(lsCalWayCdMap.get(quat.getLsCalWayCd()));
                    }
                    if(intRateWayCdMap.containsKey(quat.getIntRateWayCd())){
                        quat.setIntRateWayCdNm(intRateWayCdMap.get(quat.getIntRateWayCd()));
                    }

                    if(payWayCdMap.containsKey(quat.getPayWayCd())){
                        quat.setPayWayCdNm(payWayCdMap.get(quat.getPayWayCd()));
                    }
                    if(lsPdUntCdMap.containsKey(quat.getLsPdUntCd())){
                        quat.setLsPdUntCdNm(lsPdUntCdMap.get(quat.getLsPdUntCd()));
                    }
                    if(prdTypMap.containsKey(quat.getPrdTypCd())){
                        quat.setPrdTypCdNm(prdTypMap.get(quat.getPrdTypCd()));
                    }
                    if(null!=quat.getTotLsItmAmt()){
                        quat.setTotLsItmAmt(DecimalUtils.convertFenToYuan(quat.getTotLsItmAmt().longValue()));
                    }
                    if(null!=quat.getContAmt()){
                        quat.setContAmt(DecimalUtils.convertFenToYuan(quat.getContAmt().longValue()));
                    }
                    if(prpsQuatTypMap.containsKey(quat.getPrpsTypCd())){
                        quat.setPrpsTypCdNm(prpsQuatTypMap.get(quat.getPrpsTypCd()));
                    }
                    if (null != quat.getDsCd()) {
                        if (dsCdMap.containsKey(quat.getDsCd())) {
                            quat.setDsCdNm(dsCdMap.get(quat.getDsCd()));
                        }
                    }

                }
            }
        }

    }



    private List<CalPaySchVO>sortPayList(List<CalPaySchVO> payList){
        Collections.sort(payList, new Comparator<CalPaySchVO>(){
            public int compare(CalPaySchVO o1, CalPaySchVO o2) {
                if(o1.getPayPd() > o2.getPayPd()){
                    return 1;
                }
                if(o1.getPayPd() == o2.getPayPd()){
                    return 0;
                }
                return -1;
            }
        });
        return payList;
    }


    private CalQuatPrpsVO getTotalValue(CalQuatPrpsVO vo) {
        List<CalPaySchVO> payList = vo.getPayList();
        List<CalQuatPrpsFeeVO> detailList = vo.getFeeList();
        //合计本金、合计利息、合计剩余本金、合计租金
        double  totalRntAmt = 0d;//合计租金
        double  totalPrinAmt = 0d;//合计本金
        double  totalIntAmt = 0d;//合计利息
        double totalRemPrinAmt = 0d;//合计剩余本金
        double firstPayAmt = 0d;//首付款
        vo.setTotLsItmAmt(DecimalUtils.convertYuanToFen(vo.getTotLsItmAmt()).doubleValue());
        vo.setContAmt(DecimalUtils.convertYuanToFen(vo.getContAmt()).doubleValue());
        if(null!=vo){
            if(CollectionUtils.isNotEmpty(payList)){
                for (CalPaySchVO prjQuatPrpsPaySchVO : payList) {
                    totalRntAmt = DecimalUtils.add(totalRntAmt, prjQuatPrpsPaySchVO.getRntAmt());
                    totalPrinAmt = DecimalUtils.add(totalPrinAmt, prjQuatPrpsPaySchVO.getPrinAmt());
                    totalIntAmt = DecimalUtils.add(totalIntAmt, prjQuatPrpsPaySchVO.getIntAmt());
                    //将分转换为元
                    prjQuatPrpsPaySchVO.setPrinAmt(DecimalUtils.convertFenToYuan(prjQuatPrpsPaySchVO.getPrinAmt().longValue()));
                    prjQuatPrpsPaySchVO.setIntAmt(DecimalUtils.convertFenToYuan(prjQuatPrpsPaySchVO.getIntAmt().longValue()));
                    prjQuatPrpsPaySchVO.setRemPrinAmt(DecimalUtils.convertFenToYuan(prjQuatPrpsPaySchVO.getRemPrinAmt().longValue()));
                    prjQuatPrpsPaySchVO.setRntAmt(DecimalUtils.convertFenToYuan(prjQuatPrpsPaySchVO.getRntAmt().longValue()));
                }
            }
            //计算首付款

            if(CollectionUtils.isNotEmpty(detailList)){
                for (CalQuatPrpsFeeVO detail : detailList) {
                    //除去留购价的其他费用
                    if(detail.getCntWayCd().equals(PrjQuatPrpsConstant.CODE_PRJ_QUAT_CNT_WAY_DOWNPAY)){
                        firstPayAmt=DecimalUtils.add(detail.getFeeAmt(), firstPayAmt);
                    }
                    //转换分为元
                    detail.setFeeAmt(DecimalUtils.convertFenToYuan(detail.getFeeAmt().longValue()));
                }
            }
            vo.setFeeList(detailList);
            vo.setPayList(payList);
            vo.setActLsAmt(DecimalUtils.convertFenToYuan(Double.valueOf((vo.getActLsAmt())).longValue()));
            vo.setEachEstRntAmt(DecimalUtils.convertFenToYuan(Double.valueOf((vo.getEachEstRntAmt())).longValue()));
            vo.setTotalRntAmt(DecimalUtils.convertFenToYuan(Double.valueOf((totalRntAmt)).longValue()));
            vo.setTotalRemPrinAmt((DecimalUtils.convertFenToYuan(Double.valueOf((totalRemPrinAmt)).longValue())));
            vo.setTotalPrinAmt((DecimalUtils.convertFenToYuan(Double.valueOf((totalPrinAmt)).longValue())));
            vo.setTotalIntAmt((DecimalUtils.convertFenToYuan(Double.valueOf((totalIntAmt)).longValue())));
            vo.setFirstPayAmt(DecimalUtils.convertFenToYuan(Double.valueOf(firstPayAmt).longValue()));
            vo.setContAmt(DecimalUtils.convertFenToYuan(Double.valueOf(vo.getContAmt()).longValue()));
            vo.setTotLsItmAmt(DecimalUtils.convertFenToYuan(Double.valueOf(vo.getTotLsItmAmt()).longValue()));
        }
        return vo;
    }




}
